import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:markdown/markdown.dart' as md;

/// 代码块构建器
/// 用于将Markdown中的代码块转换为Flutter组件
class CodeBlockBuilder extends MarkdownElementBuilder {
  final TextStyle? style;
  final double? textScaleFactor;

  CodeBlockBuilder({this.style, this.textScaleFactor});

  @override
  Widget? visitElementAfter(md.Element element, TextStyle? preferredStyle) {
    // 获取代码内容和语言
    final String content = element.textContent;
    final String? language = element.attributes['class']?.replaceFirst('language-', '');
    
    return Container(
      width: double.infinity,
      margin: const EdgeInsets.symmetric(vertical: 8.0),
      padding: const EdgeInsets.all(12.0),
      decoration: BoxDecoration(
        color: Colors.grey.shade200,
        borderRadius: BorderRadius.circular(4.0),
        border: Border.all(color: Colors.grey.shade300),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (language != null)
            Padding(
              padding: const EdgeInsets.only(bottom: 8.0),
              child: Text(
                language,
                style: TextStyle(
                  color: Colors.grey.shade700,
                  fontSize: 12.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          Text(
            content,
            style: (preferredStyle ?? style)?.copyWith(
              fontFamily: 'monospace',
              color: Colors.black87,
            ),
            textScaleFactor: textScaleFactor ?? 1.0,
          ),
        ],
      ),
    );
  }
}

/// 内联代码构建器
/// 用于将Markdown中的内联代码转换为Flutter组件
class InlineCodeBuilder extends MarkdownElementBuilder {
  final TextStyle? style;
  final double? textScaleFactor;

  InlineCodeBuilder({this.style, this.textScaleFactor});

  @override
  Widget? visitElementAfter(md.Element element, TextStyle? preferredStyle) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 4.0, vertical: 2.0),
      decoration: BoxDecoration(
        color: Colors.grey.shade200,
        borderRadius: BorderRadius.circular(4.0),
      ),
      child: Text(
        element.textContent,
        style: (preferredStyle ?? style)?.copyWith(
          fontFamily: 'monospace',
          color: Colors.black87,
        ),
        textScaleFactor: textScaleFactor ?? 1.0,
      ),
    );
  }
}